package com.example.translator;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class FileNameTranslator extends JFrame {
    private final JTextField folderPathField;
    private final JTextArea logArea;
    private final JTable fileTable;
    private final FileTableModel tableModel;
    private final TranslationService translationService;
    private boolean useLangChain4j = true;
    private final ExecutorService executorService;
    private File selectedFolder;

    private Properties defaultConfig;
    private Properties currentConfig;

    public FileNameTranslator() {
        // 初始化翻译服务
        if (useLangChain4j) {
            translationService = new LangChain4jTranslationService();
            log("使用LangChain4j翻译服务");
        } else {
            translationService = new LangChain4jTranslationService();
            log("使用直接HTTP调用翻译服务");
        }
        executorService = Executors.newFixedThreadPool(5);

        // 设置窗口属性
        setTitle("文件名AI翻译助手");
        setSize(1000, 700);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建顶部面板（文件夹选择区域）
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBorder(BorderFactory.createTitledBorder("文件夹选择"));
        topPanel.setPreferredSize(new Dimension(0, 80));

        folderPathField = new JTextField();
        folderPathField.setEditable(false);
        folderPathField.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JButton browseButton = new JButton("浏览");
        browseButton.addActionListener(e -> selectFolder());

        JPanel folderPanel = new JPanel(new BorderLayout());
        folderPanel.add(folderPathField, BorderLayout.CENTER);
        folderPanel.add(browseButton, BorderLayout.EAST);

        JLabel dropLabel = new JLabel("或拖拽文件夹到此处", SwingConstants.CENTER);
        dropLabel.setForeground(Color.GRAY);
        dropLabel.setBorder(BorderFactory.createDashedBorder(Color.LIGHT_GRAY));

        topPanel.add(folderPanel, BorderLayout.NORTH);
        topPanel.add(dropLabel, BorderLayout.CENTER);

        // 设置拖放功能
        setDropTarget(new DropTarget() {
            @Override
            public synchronized void drop(DropTargetDropEvent dtde) {
                try {
                    dtde.acceptDrop(DnDConstants.ACTION_COPY);
                    List<File> droppedFiles = (List<File>) dtde.getTransferable()
                            .getTransferData(DataFlavor.javaFileListFlavor);
                    
                    if (!droppedFiles.isEmpty()) {
                        File folder = droppedFiles.get(0);
                        if (folder.isDirectory()) {
                            handleFolderSelection(folder);
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });

        // 创建中间面板（文件列表）
        JPanel middlePanel = new JPanel(new BorderLayout());
        middlePanel.setBorder(BorderFactory.createTitledBorder("文件列表及翻译结果"));

        tableModel = new FileTableModel();
        fileTable = new JTable(tableModel);
        fileTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        fileTable.getColumnModel().getColumn(0).setPreferredWidth(50);
        fileTable.getColumnModel().getColumn(1).setPreferredWidth(300);
        fileTable.getColumnModel().getColumn(2).setPreferredWidth(300);
        fileTable.getColumnModel().getColumn(3).setPreferredWidth(100);

        JScrollPane tableScrollPane = new JScrollPane(fileTable);
        middlePanel.add(tableScrollPane, BorderLayout.CENTER);

        // 创建底部面板（操作按钮和日志）
        JPanel bottomPanel = new JPanel(new BorderLayout());

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        
        JButton translateButton = new JButton("开始翻译");
        translateButton.addActionListener(e -> startTranslation());
        
        JButton renameButton = new JButton("批量重命名");
        renameButton.addActionListener(e -> batchRename());
        
        JButton exportButton = new JButton("导出对照表");
        exportButton.addActionListener(e -> exportTranslationTable());

        buttonPanel.add(translateButton);
        buttonPanel.add(renameButton);
        buttonPanel.add(exportButton);

        // 日志面板
        JPanel logPanel = new JPanel(new BorderLayout());
        logPanel.setBorder(BorderFactory.createTitledBorder("操作日志"));
        logPanel.setPreferredSize(new Dimension(0, 150));

        logArea = new JTextArea();
        logArea.setEditable(false);
        logArea.setLineWrap(true);
        JScrollPane logScrollPane = new JScrollPane(logArea);

        logPanel.add(logScrollPane, BorderLayout.CENTER);

        bottomPanel.add(buttonPanel, BorderLayout.NORTH);
        bottomPanel.add(logPanel, BorderLayout.CENTER);

        // 组装主面板
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(middlePanel, BorderLayout.CENTER);
        mainPanel.add(bottomPanel, BorderLayout.SOUTH);

        // 添加主面板到窗口
        add(mainPanel);


        // 初始化配置
        initConfig();

        // 添加菜单栏
        initMenuBar();


        // 显示窗口
        setVisible(true);

        // 初始化日志
        log("文件名AI翻译助手已启动");
        log("请选择文件夹或拖拽文件夹到窗口中");
    }

    private void selectFolder() {
        JFileChooser folderChooser = new JFileChooser();
        folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        folderChooser.setDialogTitle("选择要处理的文件夹");

        int result = folderChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFolder = folderChooser.getSelectedFile();
            handleFolderSelection(selectedFolder);
        }
    }

    private void handleFolderSelection(File folder) {
        this.selectedFolder = folder;
        folderPathField.setText(folder.getAbsolutePath());
        log("已选择文件夹: " + folder.getAbsolutePath());

        // 加载文件列表
        loadFiles(folder);
    }

    private void loadFiles(File folder) {
        log("正在加载文件列表...");
        tableModel.clear();

        File[] files = folder.listFiles();
        if (files != null && files.length > 0) {
            int loadedCount = 0;
            for (File file : files) {
                if (file.isFile()) {
                    // 检查文件名是否包含中文字符，如果包含则跳过
                    if (!containsChinese(file.getName())) {
                        tableModel.addFile(new FileInfo(file));
                        loadedCount++;
                    } else {
                        log("跳过含有中文的文件: " + file.getName());
                    }
                }
            }
            log("已加载 " + loadedCount + " 个文件（跳过 " + (files.length - loadedCount) + " 个含中文的文件）");
        } else {
            log("所选文件夹中没有文件");
        }
    }

    /**
     * 检查字符串是否包含中文字符
     */
    private boolean containsChinese(String str) {
        // 匹配中文字符的正则表达式
        String regex = "[\\u4e00-\\u9fa5]";
        return str.matches(".*" + regex + ".*");
    }

    private void startTranslation2() {
        if (selectedFolder == null) {
            JOptionPane.showMessageDialog(this, "请先选择文件夹", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        List<FileInfo> fileInfos = tableModel.getFileInfos();
        if (fileInfos.isEmpty()) {
            JOptionPane.showMessageDialog(this, "文件夹中没有文件需要翻译", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 检查API配置
        if (!translationService.isConfigured()) {
            JOptionPane.showMessageDialog(this, "OpenAI API配置不正确，请检查config.properties文件", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 显示翻译进度对话框
        JDialog progressDialog = new JDialog(this, "翻译进度", true);
        progressDialog.setSize(400, 100);
        progressDialog.setLocationRelativeTo(this);

        JPanel progressPanel = new JPanel(new BorderLayout());
        JProgressBar progressBar = new JProgressBar(0, fileInfos.size());
        progressBar.setStringPainted(true);
        progressPanel.add(new JLabel("正在翻译文件名..."), BorderLayout.NORTH);
        progressPanel.add(progressBar, BorderLayout.CENTER);
        progressDialog.add(progressPanel);

        // 启动翻译任务
        executorService.submit(() -> {
            try {
                // 在Swing事件调度线程上显示进度对话框
                SwingUtilities.invokeAndWait(() -> progressDialog.setVisible(true));

                for (int i = 0; i < fileInfos.size(); i++) {
                    FileInfo fileInfo = fileInfos.get(i);
                    String originalName = fileInfo.getOriginalName();
                    String extension = fileInfo.getExtension();

                    try {
                        // 翻译文件名（不包含扩展名）
                        String translatedName = translationService.translateFileName(originalName);

                        // 在Swing事件调度线程上更新文件信息
                        SwingUtilities.invokeAndWait(() -> {
                            fileInfo.setTranslatedName(translatedName + extension);
                            fileInfo.setTranslationStatus(true);
                        });

                        log("翻译成功: " + originalName + " -> " + translatedName + extension);
                    } catch (Exception e) {
                        // 在Swing事件调度线程上更新错误信息
                        SwingUtilities.invokeAndWait(() -> {
                            fileInfo.setTranslationStatus(false);
                            fileInfo.setErrorMsg(e.getMessage());
                        });

                        log("翻译失败: " + originalName + " - " + e.getMessage());
                    }

                    // 更新进度条
                    final int progress = i + 1;
                    int finalI = i;
                    int finalI1 = i;
                    SwingUtilities.invokeAndWait(() -> {
                        progressBar.setValue(progress);
                        progressBar.setString(progress + "/" + fileInfos.size());
                        tableModel.fireTableRowsUpdated(finalI, finalI1);
                    });

                    // 避免API调用过于频繁
                    Thread.sleep(1000);
                }

                // 在Swing事件调度线程上显示完成消息
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this, "翻译完成！", "提示", JOptionPane.INFORMATION_MESSAGE);
                });
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log("翻译任务被中断");
            } catch (Exception e) {
                log("翻译任务异常: " + e.getMessage());
            } finally {
                // 在Swing事件调度线程上关闭进度对话框
                SwingUtilities.invokeLater(() -> {
                    progressDialog.dispose();
                });
            }
        });
    }

    private void startTranslation() {
        if (selectedFolder == null) {
            JOptionPane.showMessageDialog(this, "请先选择文件夹", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        List<FileInfo> fileInfos = tableModel.getFileInfos();
        if (fileInfos.isEmpty()) {
            JOptionPane.showMessageDialog(this, "文件夹中没有文件需要翻译", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 检查API配置
        if (!translationService.isConfigured()) {
            JOptionPane.showMessageDialog(this, "OpenAI API配置不正确，请检查config.properties文件", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 创建非模态的进度对话框
        JDialog progressDialog = new JDialog(this, "翻译进度", false);
        progressDialog.setSize(400, 100);
        progressDialog.setLocationRelativeTo(this);
        progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

        JPanel progressPanel = new JPanel(new BorderLayout());
        JProgressBar progressBar = new JProgressBar(0, 100);
        progressBar.setStringPainted(true);
        progressPanel.add(new JLabel("正在翻译文件名..."), BorderLayout.NORTH);
        progressPanel.add(progressBar, BorderLayout.CENTER);
        progressDialog.add(progressPanel);

        // 在事件调度线程中显示进度对话框
        SwingUtilities.invokeLater(() -> progressDialog.setVisible(true));

        // 准备批量翻译
        List<String> fileNamesToTranslate = new ArrayList<>();
        for (FileInfo fileInfo : fileInfos) {
            fileNamesToTranslate.add(fileInfo.getOriginalName());
        }

        // 创建进度回调
        TranslationService.ProgressCallback callback = new TranslationService.ProgressCallback() {
            @Override
            public void onProgress(int current, int total, String message) {
                SwingUtilities.invokeLater(() -> {
                    progressBar.setValue(current * 100 / total);
                    progressBar.setString(String.format("%d/%d", current, total));
                    log(message);
                });
            }

            @Override
            public void onBatchComplete(int batchIndex, Map<String, String> results) {
                SwingUtilities.invokeLater(() -> {
                    // 更新对应的文件信息
                    int startIndex = batchIndex * 10;
                    results.forEach((original, translated) -> {
                        int index = fileNamesToTranslate.indexOf(original);
                        if (index >= 0) {
                            FileInfo fileInfo = fileInfos.get(index);
                            fileInfo.setTranslatedName(translated + fileInfo.getExtension());
                            fileInfo.setTranslationStatus(true);
                            tableModel.fireTableRowsUpdated(index, index);
                        }
                    });
                    log(String.format("第 %d 批翻译完成，成功翻译 %d 个文件名", batchIndex + 1, results.size()));
                });
            }

            @Override
            public void onError(int batchIndex, String error) {
                SwingUtilities.invokeLater(() -> {
                    log(String.format("第 %d 批翻译失败: %s", batchIndex + 1, error));
                    // 更新失败的文件信息
                    int startIndex = batchIndex * 10;
                    int endIndex = Math.min(startIndex + 10, fileInfos.size());
                    for (int i = startIndex; i < endIndex; i++) {
                        FileInfo fileInfo = fileInfos.get(i);
                        fileInfo.setTranslationStatus(false);
                        fileInfo.setErrorMsg(error);
                        tableModel.fireTableRowsUpdated(i, i);
                    }
                });
            }
        };

        // 启动翻译任务
        executorService.submit(() -> {
            try {
                log("开始批量翻译 " + fileNamesToTranslate.size() + " 个文件名");

                // 执行批量翻译
                Map<String, String> translationResults = translationService.batchTranslateFileNames(fileNamesToTranslate, callback);

                // 在Swing事件调度线程上显示完成消息
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this, "翻译完成！", "提示", JOptionPane.INFORMATION_MESSAGE);
                    progressDialog.dispose();
                });
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log("翻译任务被中断");
                SwingUtilities.invokeLater(() -> progressDialog.dispose());
            } catch (Exception e) {
                log("批量翻译失败: " + e.getMessage());
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this, "翻译失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    progressDialog.dispose();
                });
            }
        });
    }

    /**
     * 批量翻译失败时回退到逐个翻译
     */
    private void fallbackToIndividualTranslation(List<FileInfo> fileInfos, JProgressBar progressBar, JDialog progressDialog) {
        try {
            for (int i = 0; i < fileInfos.size(); i++) {
                FileInfo fileInfo = fileInfos.get(i);
                String originalName = fileInfo.getOriginalName();
                String extension = fileInfo.getExtension();

                try {
                    // 翻译文件名（不包含扩展名）
                    String translatedName = translationService.translateFileName(originalName);

                    // 在Swing事件调度线程上更新文件信息
                    SwingUtilities.invokeAndWait(() -> {
                        fileInfo.setTranslatedName(translatedName + extension);
                        fileInfo.setTranslationStatus(true);
                    });

                    log("翻译成功: " + originalName + " -> " + translatedName + extension);
                } catch (Exception e) {
                    // 在Swing事件调度线程上更新错误信息
                    SwingUtilities.invokeAndWait(() -> {
                        fileInfo.setTranslationStatus(false);
                        fileInfo.setErrorMsg(e.getMessage());
                    });

                    log("翻译失败: " + originalName + " - " + e.getMessage());
                }

                // 更新进度条
                final int progress = i + 1;
                int finalI = i;
                int finalI1 = i;
                SwingUtilities.invokeAndWait(() -> {
                    progressBar.setValue(progress);
                    progressBar.setString(progress + "/" + fileInfos.size());
                    tableModel.fireTableRowsUpdated(finalI, finalI1);
                });

                // 避免API调用过于频繁
                Thread.sleep(1000);
            }

            // 在Swing事件调度线程上显示完成消息
            SwingUtilities.invokeLater(() -> {
                JOptionPane.showMessageDialog(this, "翻译完成（使用逐个翻译模式）！", "提示", JOptionPane.INFORMATION_MESSAGE);
            });
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log("翻译任务被中断");
        } catch (Exception e) {
            log("逐个翻译也失败: " + e.getMessage());
        }
    }


    private void batchRename() {
        List<FileInfo> fileInfos = tableModel.getFileInfos();
        if (fileInfos.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有文件可重命名", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 检查是否有已翻译的文件
        long translatedCount = fileInfos.stream().filter(FileInfo::isTranslationStatus).count();
        if (translatedCount == 0) {
            JOptionPane.showMessageDialog(this, "请先执行翻译操作", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 确认重命名操作
        int confirm = JOptionPane.showConfirmDialog(this,
                "确定要将 " + translatedCount + " 个文件重命名吗？\n此操作不可撤销！",
                "确认重命名", JOptionPane.YES_NO_OPTION);

        if (confirm == JOptionPane.YES_OPTION) {
            log("开始批量重命名...");
            int successCount = 0;
            int failCount = 0;

            for (FileInfo fileInfo : fileInfos) {
                if (fileInfo.isTranslationStatus()) {
                    try {
                        File originalFile = new File(selectedFolder, fileInfo.getOriginalName() + fileInfo.getExtension());
                        File newFile = new File(selectedFolder, fileInfo.getTranslatedName());

                        if (originalFile.renameTo(newFile)) {
                            successCount++;
                            log("重命名成功: " + originalFile.getName() + " -> " + newFile.getName());
                        } else {
                            failCount++;
                            log("重命名失败: " + originalFile.getName());
                        }
                    } catch (Exception e) {
                        failCount++;
                        log("重命名异常: " + fileInfo.getOriginalName() + " - " + e.getMessage());
                    }
                }
            }

            log("批量重命名完成: 成功 " + successCount + " 个，失败 " + failCount + " 个");
            JOptionPane.showMessageDialog(this,
                    "批量重命名完成！\n成功: " + successCount + " 个\n失败: " + failCount + " 个",
                    "结果", JOptionPane.INFORMATION_MESSAGE);

            // 重新加载文件列表
            loadFiles(selectedFolder);
        }
    }

    private void exportTranslationTable() {
        List<FileInfo> fileInfos = tableModel.getFileInfos();
        if (fileInfos.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有数据可导出", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择导出文件路径");
        fileChooser.setSelectedFile(new File("文件名翻译对照表.csv"));

        int result = fileChooser.showSaveDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File exportFile = fileChooser.getSelectedFile();
            try {
                ExportService.exportToCSV(fileInfos, exportFile);
                log("已导出翻译对照表到: " + exportFile.getAbsolutePath());
                JOptionPane.showMessageDialog(this, "导出成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                log("导出失败: " + e.getMessage());
                JOptionPane.showMessageDialog(this, "导出失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    public void log(String message) {
        SwingUtilities.invokeLater(() -> {
            logArea.append("[" + java.time.LocalTime.now() + "] " + message + "\n");
            logArea.setCaretPosition(logArea.getDocument().getLength());
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(FileNameTranslator::new);
    }

    private void initConfig() {
        // 加载默认配置
        defaultConfig = new Properties();
        try (InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties")) {
            if (input != null) {
                defaultConfig.load(input);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        // 初始使用默认配置
        currentConfig = new Properties(defaultConfig);
    }

    private void initMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        JMenu settingsMenu = new JMenu("设置");

        JMenuItem configItem = new JMenuItem("OpenAI配置");
        configItem.addActionListener(e -> showConfigDialog());
        settingsMenu.add(configItem);

        menuBar.add(settingsMenu);
        setJMenuBar(menuBar);
    }

    private void showConfigDialog() {
        ConfigDialog dialog = new ConfigDialog(this, defaultConfig);
        dialog.setVisible(true);

        if (dialog.isConfirmed()) {
            if (dialog.isUseCustomConfig()) {
                currentConfig = dialog.getConfig();
                log("已切换到自定义配置");
            } else {
                currentConfig = new Properties(defaultConfig);
                log("已切换到默认配置");
            }

            // 更新翻译服务的配置
            updateTranslationServiceConfig();
        }
    }

    private void updateTranslationServiceConfig() {
        try {
            translationService.updateConfig(currentConfig);
            defaultConfig = currentConfig;
            log("配置更新成功");
        } catch (Exception e) {
            log("配置更新失败: " + e.getMessage());
            JOptionPane.showMessageDialog(this, "配置更新失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
